package online.sixfish.doubao.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import online.sixfish.common.api.ApiErrorCode;
import online.sixfish.common.dto.PageDTO;
import online.sixfish.common.exception.ApiAsserts;
import online.sixfish.common.exception.CommonConstant;
import online.sixfish.common.utils.SecurityUtil;
import online.sixfish.doubao.mapper.CoursewareMapper;
import online.sixfish.doubao.model.entity.Courseware;
import online.sixfish.doubao.service.CoursewareService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Objects;

@Service
public class CoursewareServiceImpl implements CoursewareService {
    private static final String FILE_PATH = "C:\\Users\\13326\\Documents\\courseware\\";
    @Resource
    CoursewareMapper coursewareMapper;
    private static final String INCREMENT_HEAT_SQL_PATTERN="heat=heat+{0}";

    @Override
    public PageDTO list(String type, String name, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Courseware> queryWrapper =
                new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(type)) {
            queryWrapper.eq(Courseware::getType, type);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(Courseware::getName, name);
        }
        queryWrapper.ne(Courseware::getStatus,CommonConstant.SYS_ILLEGAL_STATUS);
        queryWrapper.orderByDesc(Courseware::getHeat);

        Page<Courseware> page = new Page<>(pageNum, pageSize);
        coursewareMapper.selectPage(page, queryWrapper);
        PageDTO<Courseware> pageDTO = PageDTO.build(page);
        return pageDTO;

    }

    @Override
    public void upload(MultipartFile file,String info) {
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();
        String suffix = FileNameUtil.getSuffix(originalFilename);
        String uuid = UUID.randomUUID().toString();
        String newName = uuid + "." + suffix;
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_PATH + newName);
            Files.write(path, bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Courseware courseware = new Courseware();
        courseware.setName(originalFilename);
        courseware.setSize(size);
        courseware.setUserId(SecurityUtil.currentUserId());
        courseware.setType(suffix);
        courseware.setUrl(FILE_PATH+newName);
        courseware.setInfo(info);
        coursewareMapper.insert(courseware);

    }

    @Override
    public byte[] download(Integer id) throws IOException {
        Courseware courseware = coursewareMapper.selectById(id);
        if(Objects.isNull(courseware)){
            ApiAsserts.fail(ApiErrorCode.NOT_FOUND);
        }
        return FileUtils.readFileToByteArray(new File(courseware.getUrl()));

    }

    @Override
    public Courseware findById(Integer id) {
        return coursewareMapper.selectById(id);
    }

    @Override
    public void incrementHeat(Integer id, int num) {
        LambdaUpdateWrapper<Courseware> wrapper = Wrappers
                .lambdaUpdate(Courseware.class).eq(Courseware::getId, id);
        String sql = MessageFormat.format(INCREMENT_HEAT_SQL_PATTERN, num);
        wrapper.setSql(sql);
        coursewareMapper.update(null,wrapper);
    }

    @Override
    public void update(Courseware courseware) {
        Courseware c = coursewareMapper.selectById(courseware.getId());
        String type = c.getType();
        courseware.setName(courseware.getName()+'.'+type);
        coursewareMapper.updateById(courseware);
    }

    @Override
    public void delete(Integer id) {
        Courseware courseware = new Courseware();
        courseware.setId(id);
        courseware.setStatus(CommonConstant.SYS_ILLEGAL_STATUS);
        coursewareMapper.updateById(courseware);
    }
}
